/**$6
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 */



#include "Config.h"
#include "init.h"



/**
 =======================================================================================================================
 *
 =======================================================================================================================
 */
void init(void)
{
#if defined(__C30__)
	AD1PCFG = 0xffff;		/* disabilita AN */

	/* initialize IO pin mappings */
	RPOR7bits.RP15R = 18;	/* OC1 on RP15 */
	RPINR18bits.U1RXR = 10; /* UART1 RX on RP10 */
	RPOR5bits.RP11R = 3;	/* UART1 TX on RP11 */
	OSCCONbits.IOLOCK = 1;
	uart1_init_pic24((unsigned int)415,(char) 0x06,(char) 0x05);

	/* start system timer - 1 ms resolution */
	IFS0bits.T1IF = 0;
	//IEC0bits.T1IE = 1;
	IPC0bits.T1IP = 0x07;
	T1CONbits.TCKPS1 = 1;
	T1CONbits.TCKPS0 = 0;
	T1CONbits.TCS = 0;
	PR1 = 25000 - 1;
	T1CONbits.TON = 1;

	/* FIXME Set directions of UART IOs */
	TRISBbits.TRISB3 = 0;
	TRISBbits.TRISB2 = 1;
	AD1PCFGbits.PCFG9 = 1;
	TRISBbits.TRISB0 = 1;
#elif defined(__18CXX)
	CMCON = 0b00000111;	/* Close Comparator */
	TRISA = 0b00010000;	/* Configure PORTA I/O */
	TRISB = 0b00000001;	/* Configure PORTB I/O */
	TRISC = 0b11000000;	/* Configure PORTC I/O */
	TRISD = 0b00000000;	/* Configure PORTD I/O */
	TRISE = 0b00001000;	/* Configure PORTE I/O */
	ADCON1 = 0b00001111;	/* Enable digital I/O */
	SPBRG = 64; /* Transmission choices for the Baud Rate 4800bps(SPBRG=(20000000/ 4800/64)-1) */
	BAUDCONbits.BRG16 = 0;	/* Choice 8-bit baud rate generator */
	TXSTAbits.BRGH = 0;		/* High Baud Rate */
	TXSTAbits.SYNC = 0;		/* Asynchronous mode */
	RCSTAbits.SPEN = 1;		/* Enable Serial Port */
	TXSTAbits.TX9 = 0;		/* 8-bit Transmission */
	RCSTAbits.CREN = 1;		/* Enable Serial receiver */
	RCSTAbits.RX9 = 0;		/* 8 bit */
	PIE1bits.RCIE = 1;		/* Enable Interrupt */
	INTCONbits.GIE = 1;
	INTCONbits.PEIE = 1;

	/*
	 * TXSTAbits.TXEN=1;
	 * // Enable Transmission
	 */
#endif
}

#if defined(__C30__)

/**
 =======================================================================================================================
 *
 =======================================================================================================================
 */
void uart1_init_pic24(unsigned int baud, char rx_priority, char tx_priority)
{
	IPC2bits.U1RXIP = rx_priority;
	IPC3bits.U1TXIP = tx_priority;
	IEC0bits.U1RXIE = 1;

	/* reset RX flag */
	IFS0bits.U1RXIF = 0;

	/* Activated by the driver */
	IEC0bits.U1TXIE = 0;
	U1STAbits.UTXISEL0 = 1;
	U1BRG = baud;
	U1MODEbits.BRGH = 1;
	U1MODEbits.UARTEN = 1;
	U1STAbits.UTXEN = 1;
}
#endif
